<?php
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
defined('_JEXEC') or die;
 
if (!class_exists('DatasetModel')) require ( JPATH_COMPONENT.DS.'models'.DS.'dataset.php');

 
class PmapiModelUsers extends DatasetModel
{
    /**
     * Get the master query for retrieving a list of products.
     */
    function getListQuery()
    {
        $userId = JFactory::getUser()->id;
        $db = $this->getDbo();
        
        $conditions  = "virtuemart_user_id = $userId";      // always include yourself 
        $conditions .= " OR user_is_vendor > 0";            // always include all vendors
        
        // test if current user permission to add further data..
        if ($userId){  
            if (!class_exists('Permissions')) 
                require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'permissions.php');
            $perms = Permissions::getInstance();
            $perms->getPermissions(); // loads current user permission
            
            if( $perms->isSuperVendor()) {
                // if a super vendor show alll user
                $conditions = 'virtuemart_user_id > 0';   
            } elseif ($perms->check('storeadmin')) {
                //get additional info about current user
                $vendorId = $db
                    ->setQuery( 
                        $db->getQuery(true)            
                            ->select('virtuemart_vendor_id')
                            ->from( '#__virtuemart_vmusers' )
                            ->where( "virtuemart_user_id = $userId")
                      )
                    ->loadResult();
                if ($vendorId){
                    // if it is a shopper admin get all vendor users
                    $condition .= ' OR virtuemart_vendor_id = '.$vendorId;
                }                
            }
        }
                  
        return  $db
            ->getQuery(true)
            ->select('virtuemart_user_id')
            ->from( '#__virtuemart_vmusers' )
            ->where( $conditions);
    }         
}